# -*- coding: utf-8 -*-
import os
import sys,re

my_proj_src = sys.argv[1]
platform_Name = sys.argv[2]
bundle_name = sys.argv[3]
game_name = sys.argv[4]
game_version = sys.argv[5]
for_add_sdk_folder = sys.argv[6]
confuse_oc = sys.argv[7]
useiReSign = sys.argv[8]
ipa_count = sys.argv[9]
target_name = sys.argv[10]
my_src_name = "proj.ios_appstore_" + platform_Name
my_cmd_src = '${basepath%/*}"/"'

lua_packages = [
    
    "mobileprovisionDirectory",
]
allInfoList = []
archiveInfoList = []
ipaInfoList = []

des_path = os.path.join(for_add_sdk_folder, platform_Name)

def setArchive(fileName,SignCerName,signCerUUID):
    archiveInfoList.append('''xcodebuild archive -scheme "${Target_Name}" -configuration "${Configuration}" -archivePath "${Cmd_Src}""${Plat_Name}""/archive/"${Plat_Name}''' + '"_' + fileName + '" '
        + 'CODE_SIGN_IDENTITY="${' + SignCerName + '}" PROVISIONING_PROFILE="${' + signCerUUID + '}" >> ${log_path}"' + fileName + '.txt"')


def setIpa(fileName,plistName,signName):
    ipaInfoList.append('''xcodebuild -exportArchive -archivePath "${Cmd_Src}""${Plat_Name}""/archive/"${Plat_Name}"_''' + fileName + '''"".xcarchive" -exportPath "./"${Plat_Name}"/"${ls_date} -exportOptionsPlist $''' + plistName 
                       + '\n' + '''mv "./"${Plat_Name}"/"${ls_date}"/""${Target_Name}".ipa "./"${Plat_Name}"/"${ls_date}"/""${''' + signName + '''}""_"${Game_Version}"_"${ls_date}.ipa''')


def setMajorInfo(fileName,var):

    str1 = getContentByKey(var,"<key>Name</key>","</string>").split("<string>")[1]
    str2 = getContentByKey(var,"<key>UUID</key>","</string>").split("<string>")[1]

    str3 = getContentByKey(var,"<key>ApplicationIdentifierPrefix</key>","</string>").split("<string>")[1]
    cmd_line = "security find-identity -p codesigning /Users/admin/Library/Keychains/login.keychain"


    SignCerName = ""
    signCerUUID = ""
    for lines in os.popen(cmd_line).read().split('"'):
        if lines.find(str3) > 0:
            #print lines
            print str3
            SignCerName = fileName + '_sign_identity'
            allInfoList.append(fileName + '_sign_identity="' + lines + '"')
            break


    allInfoList.append(fileName + '_name="' + str1 + '"')
    allInfoList.append(fileName + '_uuid="' + str2 + '"')

    signCerUUID = fileName + '_uuid'

    
    allInfoList.append(fileName + "=./" + fileName + ".plist")
    allInfoList.append(fileName + "=${" + fileName + "}")
    allInfoList.append(fileName + "_Options=./" + fileName + "_Options.plist")
    allInfoList.append(fileName + "_Options=${" + fileName + "_Options}")

    setArchive(fileName,SignCerName,signCerUUID)
    setIpa(fileName,fileName + "_Options",fileName + '_name')


    return str1

def saveLines(lines, savePath):
    
    h = open(savePath, "wb")
    for l in lines:
        h.write(l)
    h.close()

def saveLines2(lines, savePath):
    
    h = open(savePath, "wb")
    for l in lines:
        #l.ljust(0)
        h.write(l)
        h.write("\n")
    h.close()

def getContentByKey(l_str,key1,key2):
    return l_str.split(key1)[1].split(key2)[0]

def setPlist(var,typeStr,signVar,signName):
    lines1 = []
    lines1.append(var.split('<plist version="1.0">')[0])
    lines1.append('<plist version="1.0">')
    lines1.append(getContentByKey(var,"<key>Entitlements</key>","<key>ExpirationDate</key>"))
    lines1.append('''
</plist>''')
                
    saveLines(lines1, os.path.join(des_path, signVar + ".plist"))


    lines2 = []
    lines2.append('''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict> 
    <key>provisioningProfiles</key>
    <dict>''')
    lines2.append("\n" + '''    <key>'''+ bundle_name + '''</key>''')
    lines2.append("\n" + '''    <string>'''+ signName + '''</string>''')
    lines2.append(''' 
    </dict> 
    <key>method</key>
    <string>''' + typeStr) 
    lines2.append('''</string>
</dict> 
</plist>''')
    saveLines(lines2, os.path.join(des_path, signVar + "_Options.plist"))



def walkFolder(rootDir, deltaPath):

    thedirs = os.listdir(rootDir)
    thedirs.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))

    for lists in thedirs:
        path = os.path.join(rootDir, lists)
        if not os.path.isdir(path):
            prev, extName = os.path.splitext(lists)
            if deltaPath != "" and extName == ".mobileprovision":
                #print prev, extName
                
                var = os.popen("security cms -D -i " + os.path.join(for_add_sdk_folder, "mobileprovisionDirectory/") + lists).read()

                signVar = 'IOS_' + prev
                signName = ""
                signName = setMajorInfo(signVar,var)
                allInfoList.append("\n")
                

                # Our check
                if var.find("<key>ProvisionsAllDevices</key>") != -1:

                    setPlist(var,"enterprise",signVar,signName)

                # App Store
                elif var.find("<key>beta-reports-active</key>") != -1:
                    setPlist(var,"app-store",signVar,signName)
                #Ad Hoc
                else:
                    setPlist(var,"ad-hoc",signVar,signName)
                    

                
if __name__ == "__main__":

    allInfoList.append('#/bin/sh')

    allInfoList.append('#项目路径')
    allInfoList.append('Proj_Src="' + my_proj_src + '"')
    allInfoList.append('#项目目录')
    allInfoList.append('Proj_Src_Name="' + my_src_name + '"')
    allInfoList.append('#脚本路径')
    allInfoList.append('basepath=$(cd `dirname $0`; pwd)')
    allInfoList.append('Cmd_Src=' + my_cmd_src)
    allInfoList.append('#Target名字')
    allInfoList.append('Target_Name="' + target_name + '"')
    allInfoList.append('#平台名')
    allInfoList.append('Plat_Name="' + platform_Name + '"')
    allInfoList.append('#游戏名')
    allInfoList.append('Game_Name="' + game_name + '"')
    allInfoList.append('#GameVersion')
    allInfoList.append('Game_Version="' + game_version + '"')
    allInfoList.append('#配置环境，Release或者Debug')
    allInfoList.append('Configuration="Release"')
    allInfoList.append('#ipa包数量')
    allInfoList.append('Ipa_count=' + ipa_count)
    allInfoList.append('#描述文件路径')
    allInfoList.append('Profiles_Src="/Users/admin/Library/MobileDevice/Provisioning Profiles/"')
    allInfoList.append('\n')
    os.system("mkdir " + des_path)
    print os.getcwd()
    for subPackage in lua_packages:
        walkFolder(
            os.path.join(for_add_sdk_folder, subPackage),
            subPackage
        )


    allInfoList.append('''
#时间
ls_date=`date +%Y_%m_%d_%H_%M`
echo ${ls_date}
cd "${Proj_Src}""${Proj_Src_Name}"
#log
log_path=${Cmd_Src}${Plat_Name}"/"
''')

    if confuse_oc == "confuseOC":
        allInfoList.append('''
echo "start to confuse OC"
"${Cmd_Src}""${Plat_Name}""/confusion/confusion.rb" "${Proj_Src}""${Proj_Src_Name}""/arpg.xcodeproj"
echo "end confuse OC"
''')
    
    allInfoList.append('''
#archive
echo "start archive"
rm -rf "${Cmd_Src}""${Plat_Name}""/archive"''')
    for lines in archiveInfoList:
        allInfoList.append(lines)
    allInfoList.append('''cd "${Cmd_Src}""${Plat_Name}"''')
    

    allInfoList.append('''
#打包
echo "start exportArchive"
rm -rf "${Cmd_Src}""${Plat_Name}""/${Plat_Name}"''')
    for lines in ipaInfoList:
        allInfoList.append(lines)

    if useiReSign == "useiReSign":
        allInfoList.append('''\ncd "${Cmd_Src}""${Plat_Name}""/""${Plat_Name}"
rm -rf ./${ls_date}/DistributionSummary.plist
rm -rf ./${ls_date}/ExportOptions.plist
rm -rf ./${ls_date}/Packaging.log
echo "start to resign"
"${Cmd_Src}""${Plat_Name}""/iReSign/resign.rb" "${Cmd_Src}""${Plat_Name}""/""${Plat_Name}""/""${ls_date}"
''')
    else:
        allInfoList.append('''\ncd "${Cmd_Src}""${Plat_Name}""/""${Plat_Name}"
rm -rf ./${ls_date}/DistributionSummary.plist
rm -rf ./${ls_date}/ExportOptions.plist
rm -rf ./${ls_date}/Packaging.log
''')

    allInfoList.append('''\ncount=0
while [[ $count != $Ipa_count ]]; do
    sleep 5
    count=0
    file_list=`ls "${Cmd_Src}""${Plat_Name}""/"${Plat_Name}"/"${ls_date}`
    for file in $file_list; do
        suffix=${file##*.}
        if [[ ${suffix} = "ipa" ]]; then
            count=$[count+1]
        fi 
    done
done
zip ${Game_Name}${Plat_Name}"_"${Game_Version}"_"${ls_date}.zip ${ls_date}/*
''')

    saveLines2(allInfoList, os.path.join(des_path, platform_Name + ".sh"))


    runInfo = []
    runInfo.append('#!/usr/bin/env bash\n' + 'Proj_Src="' + my_proj_src.split("/frameworks/runtime-src/")[0] + '"\n' + 'BundleID="' + bundle_name + '"\n' + 'Plat_Name="' + platform_Name + '"\n' + 'basepath=$(cd `dirname $0`; pwd)\n' + 'Cmd_Src=' + my_cmd_src + '\n' + '''
Runtime_Src="${Proj_Src}""/frameworks/runtime-src/"

echo "remove old project and Classes"
rm -rf "${Runtime_Src}""proj.ios_appstore_${Plat_Name}"
rm -rf "${Runtime_Src}""Classes"

svn up ${Proj_Src}
ls_date=`date +%Y_%m_%d_%H_%M`
echo ${ls_date}
chmod -R 777 ${Proj_Src}/frameworks/cocos2d-x/tools/cocos2d-console/
chmod -R 777 ${Proj_Src}/tools
chmod -R 777 ${Proj_Src}
${Proj_Src}/tools/avc/mac/ccappstore "${Proj_Src}""/frameworks"
#/Users/cc/ccwork/python/arpgVersionControl/mac/macpublish b2 "/Users/cc/ccwork/b2/0.3.9" "/Users/cc/ccwork/b2/0.3.9/../avcresult" "ios_qudaoceshi/" "arpg.xcodeproj" "arpg iOS" "iPhone Distribution: Wenping Xiao (5QKE3SEQ82)" "iPhone Distribution: Wenping Xiao (5QKE3SEQ82)" "false" "false" 1.0.0.1583 qudaoceshi 1.0.5 gmzh.dis gmzh.dis ${ls_date} "b2.aipiou.cn" "com.kuaiyou.gmzh"
# ${Proj_Src}/tools/avc/mac/macpublish b2 "${Proj_Src}" "/Users/admin/b2_branch/avcresult" "ios_qudaoceshi/" "arpg.xcodeproj" "arpg iOS" "iPhone Distribution: kang zhao (C4N82CY4WV)" "iPhone Distribution: kang zhao (C4N82CY4WV)" "false" "false" 1.0.0.2632 qudaoceshi 1.0.0 allDis_20171115 allDis_20171115 ${ls_date} "b2.aipiou.cn" "${BundleID}" -z 6
chmod -R 777 ${Proj_Src}
${Cmd_Src}${Plat_Name}/${Plat_Name}".sh"
${Proj_Src}/tools/avc/mac/ccappstore "${Proj_Src}""/frameworks" -r "true"

''')
    saveLines2(runInfo, os.path.join(des_path, "run.sh"))

    os.system("chmod -R 777 " + des_path)
